package puc.redes.examples.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPClient1 {

	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;

	TCPClient1() {
	}

	void run() {
		try {
			// 1. Creamos un socker de conexion con el servidor
			requestSocket = new Socket("127.0.0.1", 2512);
			System.out.println("Conectados a localhost, puerto 2512" );
			
			// 2. obtenermos los stream de entrada y salida del socker
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			
			// 3: Nos comunicamos con el servidor
			do {
				try {
					message = (String) in.readObject();
					System.out.println("servidor: " + message);
					
					// enviamos mensajes
					sendMessage("Hola servidor");
					message = "chau";
					sendMessage(message);
				} catch (ClassNotFoundException classNot) {
					System.err.println("Datos recibidos en formato desconocido");
				}
			} while (!message.equals("chau"));
		} catch (UnknownHostException unknownHost) {
			System.err.println("desconozco el host!");
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			// 4: Cerramos la conexion
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("cliente: " + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

	public static void main(String args[]) {
		TCPClient1 client = new TCPClient1();
		client.run();
	}

}
